package com.dubito.gallery

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.android.volley.Request
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson

/**
 *author: liliang
 *date: 2020/11/13 10:49 PM
 *
 */
class GalleryViewModel(application: Application) : AndroidViewModel(application) {

    private val keywords =
        arrayOf("cat", "dog","girl")

    private val _photosLiveData = MutableLiveData<List<PhotoItem>>()

    val photosLiveData: LiveData<List<PhotoItem>>
        get() = _photosLiveData

    fun fetchData() {
        val stringRequest = StringRequest(Request.Method.GET, getUrl(), {
            _photosLiveData.value = Gson().fromJson(it, Pixabay::class.java).hits.toList()
        }, {
            Log.d("TAG", "fetchData: $it")
        })
        VolleySingleton.getInstance(getApplication()).requestQueue.add(stringRequest)
    }

    private fun getUrl() =
        "https://pixabay.com/api/?key=19100761-e60144dec5c8c4121e55ddd4f&q=${keywords.random()}&per_page=200"

}